import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';
import 'package:macless_haystack/accessory/accessory_model.dart';
import 'package:macless_haystack/item_management/refresh_action.dart';
import 'package:provider/provider.dart';
import 'package:macless_haystack/accessory/accessory_registry.dart';
import 'package:macless_haystack/dashboard/accessory_map_list_vert.dart';
import 'package:macless_haystack/item_management/item_management.dart';
import 'package:macless_haystack/item_management/new_item_action.dart';
import 'package:macless_haystack/location/location_model.dart';
import 'package:macless_haystack/preferences/preferences_page.dart';
import 'package:macless_haystack/preferences/user_preferences_model.dart';
import 'package:macless_haystack/platform_stub.dart'  
    if (dart.library.html) 'package:macless_haystack/platform_web.dart' as web;


class Dashboard extends StatefulWidget {
  /// Displays the layout for the mobile view of the app.
  ///
  /// The layout is optimized for a vertically aligned small screens.
  /// The functionality is structured in a bottom tab bar for easy access
  /// on mobile devices.
  const Dashboard({super.key});

  @override
  State<StatefulWidget> createState() {
    return _DashboardState();
  }
}

class _DashboardState extends State<Dashboard> {
  /// A list of the tabs displayed in the bottom tab bar.
  late final List<Map<String, dynamic>> _tabs = [
    {
      'title': '我的定位标签',
      'body': (ctx) => AccessoryMapListVertical(
            loadLocationUpdates: loadLocationUpdates,
            loadVisibleItemsLocationUpdates: loadVisibleItemsLocationUpdates,
            loadOneLocationUpdates: loadOneLocationUpdates,
          ),
      'icon': Icons.place,
      'label': '地图',
      'actionButton': (ctx) => RefreshAction(
            // callback: loadLocationUpdates,
            callback: loadVisibleItemsLocationUpdates,
          ),
    },
    {
      'title': '我的定位标签',
      'body': (ctx) => const KeyManagement(),
      'icon': Icons.style,
      'label': '定位标签',
      'actionButton': (ctx) => const NewKeyAction(),
    },
  ];

  @override
  void initState() {
    super.initState();

    // Initialize models and preferences
    var userPreferences = Provider.of<UserPreferences>(context, listen: false);
    var locationModel = Provider.of<LocationModel>(context, listen: false);
    var locationPreferenceKnown =
        userPreferences.locationPreferenceKnown ?? false;
    var locationAccessWanted = userPreferences.locationAccessWanted ?? false;
    if (!locationPreferenceKnown || locationAccessWanted) {
      locationModel.requestLocationUpdates();
    }

    // Load new location reports on app start
    // loadLocationUpdates();
  }

  /// Fetch location updates for visible accessories.
  Future<void> loadVisibleItemsLocationUpdates() async {
    var accessoryRegistry =
        Provider.of<AccessoryRegistry>(context, listen: false);
    accessoryRegistry.loadedAccessoryIds.clear();
    for (var accessory in accessoryRegistry.visibleAccessories) {
      //accessoryRegistry.loadedAccessoryIds.add(accessory.id);
      //loadOneLocationUpdates(accessory);

      if (!accessory.isLoadingReports) {
        accessory.isLoadingReports = true;
        accessoryRegistry.asyncQueue.add(() {
          if (accessoryRegistry.visibleAccessories.contains(accessory) &&
              !accessoryRegistry.loadedAccessoryIds.contains(accessory.id)) {
            accessoryRegistry.loadedAccessoryIds.add(accessory.id);
            return loadOneLocationUpdates(accessory);
          } else {
            accessory.isLoadingReports = false;
          }

          return Future.value();
        });
      }
    }
  }

  var logger = Logger(
    printer: PrettyPrinter(),
  );

  /// Fetch location updates for one accessory.
  Future<void> loadOneLocationUpdates(Accessory accessory) async {
    var accessoryRegistry =
        Provider.of<AccessoryRegistry>(context, listen: false);

    String? url = Settings.getValue<String>(endpointUrl);
    String? urlfallback = Settings.getValue<String>(endpointUrlFallback);
    try {
      await accessoryRegistry.loadOneLocationReports(accessory);
    } catch (e, stacktrace) {
      logger.e('Error on fetching', error: e, stackTrace: stacktrace);

      var errMsg = e.toString();
      if (e is HttpException) {
        errMsg = e.message;
        if (errMsg == 'Connection closed before full header was received') {
          errMsg = 'AppleID 登录可能失效，请移除 auth.json 并重启 macless-haystack 服务';
        }
      }

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: Theme.of(context).colorScheme.error,
          content: Text(
            '未获取到位置。${errMsg}',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onError,
            ),
          ),
        ),
      );
    }
  }

  /// Fetch location updates for all accessories.
  Future<void> loadLocationUpdates(Accessory? accessory) async {
    var accessoryRegistry =
        Provider.of<AccessoryRegistry>(context, listen: false);
    var inactive = 0;
    Iterable<Accessory> accessories;
    if (accessory == null) {
      accessories = accessoryRegistry.accessories;
      inactive = accessories.where((a) => !a.isActive).length;
    } else {
      accessories = [accessory];
    }
    var accs = accessories.where((a) => a.isActive);
    for (var a in accs) {
      a.isLoadingReports = true;
    }
    try {
      var count = await accessoryRegistry.loadLocationReports(accs);
      if (mounted && accessoryRegistry.accessories.isNotEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Theme.of(context).colorScheme.primary,
            content: Text(
              '获取到 $count 条位置。${inactive > 0 ? '已跳过 $inactive 个未激活的标签' : ''}',
              style: TextStyle(
                color: Theme.of(context).colorScheme.onPrimary,
              ),
            ),
          ),
        );
      }
    } catch (e, stacktrace) {
      logger.e('Error on fetching', error: e, stackTrace: stacktrace);
      var errMsg = e.toString();
      if (e is HttpException) {
        errMsg = e.message;
        if (errMsg == 'Connection closed before full header was received') {
          errMsg = 'AppleID 登录失效，请移除 auth.json 并重启 macless-haystack 服务';
        }
      }
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Theme.of(context).colorScheme.error,
            content: Text(
              '未获取到位置。$errMsg',
              style: TextStyle(
                color: Theme.of(context).colorScheme.onError,
              ),
            ),
          ),
        );
      }
    } finally {
      for (var a in accs) {
        a.isLoadingReports = false;
      }
    }
  }

  /// The selected tab index.
  int _selectedIndex = 0;

  bool _searchBoolean = false;
  List<int> _searchIndexList = [];

  /// Updates the currently displayed tab to [index].
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  Widget _searchTextField() {
    //add
    return TextField(
      onChanged: (String s) {
        var accessories =
            Provider.of<AccessoryRegistry>(context, listen: false).accessories;
        setState(() {
          _searchIndexList = [];
          for (int i = 0; i < accessories.length; i++) {
            if (accessories[i].name.toLowerCase().contains(s.toLowerCase())) {
              _searchIndexList.add(i);
            }
          }
        });
      },
      autofocus: true, //Display the keyboard when TextField is displayed
      /* cursorColor: Colors.white,
      style: TextStyle(
        color: Colors.white,
        fontSize: 20,
      ), */
      textInputAction:
          TextInputAction.search, //Specify the action button on the keyboard
      decoration: InputDecoration(
        //Style of TextField
        enabledBorder: UnderlineInputBorder(//Default TextField border
            //borderSide: BorderSide(color: Colors.white)
            ),
        focusedBorder:
            UnderlineInputBorder(//Borders when a TextField is in focus
                //borderSide: BorderSide(color: Colors.white)
                ),
        hintText: '搜索', //Text that is displayed when nothing is entered.
        hintStyle: TextStyle(
          //Style of hintText
          color: Colors.black54,
          fontSize: 20,
        ),
      ),
    );
  }

  Widget _searchListView() {
    return Consumer<AccessoryRegistry>(
      builder: (context, accessoryRegistry, child) {
        var accessories = accessoryRegistry.accessories;
        return ListView.builder(
            itemCount: _searchIndexList.length,
            itemBuilder: (context, index) {
              var idx = _searchIndexList[index];
              return ListTile(
                  title: Text(accessories[idx].name),
                  onTap: () {
                    setState(() {
                      _searchBoolean = false;
                      _searchIndexList = [];
                    });

                    var accessoryRegistry =
                        Provider.of<AccessoryRegistry>(context, listen: false);
                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      accessoryRegistry.eventBus
                          .fire(JumpToListItemEvent(_selectedIndex, idx));
                    });
                  });
            });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false, // 禁止默认的返回行为
        onPopInvokedWithResult: (bool didPop, Object? result) async {
          if (!didPop) {
            final navigator = Navigator.of(context);
            if (!_searchBoolean) {
              if (navigator.canPop()) {
                navigator.pop();
              } else {
                exit(0);
              }
            } else {
              setState(() {
                _searchBoolean = false;
              });
            }
          }
        },
        child: Scaffold(
          appBar: AppBar(
              title: !_searchBoolean
                  ? Text(_tabs[_selectedIndex]['title'])
                  : _searchTextField(), // const Text('我的定位标签'),
              actions: !_searchBoolean
                  ? [
                      IconButton(
                          icon: Icon(Icons.search),
                          onPressed: () {
                            setState(() {
                              _searchBoolean = true;
                              _searchIndexList = [];
                            });
                          }),
                      IconButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const PreferencesPage()),
                          );
                        },
                        icon: const Icon(Icons.settings),
                      ),
                    ]
                  : [
                      IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            setState(() {
                              _searchBoolean = false;
                            });
                          })
                    ]),
          body: !_searchBoolean
              ? _tabs[_selectedIndex]['body'](context)
              : _searchListView(),
          bottomNavigationBar: !_searchBoolean
              ? BottomNavigationBar(
                  items: _tabs
                      .map((tab) => BottomNavigationBarItem(
                            icon: Icon(tab['icon']),
                            label: tab['label'],
                          ))
                      .toList(),
                  currentIndex: _selectedIndex,
                  unselectedItemColor: Theme.of(context).unselectedWidgetColor.withValues(alpha: .3),
                  onTap: _onItemTapped,
                )
              : null,
          floatingActionButton: !_searchBoolean
              ? _tabs[_selectedIndex]['actionButton']?.call(context)
              : null,
        ));
  }
}
